package com.keepc.licence.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 文件及文件流获取工具类
 */
public class FileUtils {

    private static final String CLASSPATH_RESOURCE_PREFIX = "classpath:";

    public static File getFile(String path) throws IOException {
        if (StringUtils.isEmpty(path)) {
            throw new FileNotFoundException("未找到文件路径");
        }
        if (path.startsWith(CLASSPATH_RESOURCE_PREFIX)) {
            return new ClassPathResource(path.replaceAll(CLASSPATH_RESOURCE_PREFIX, "")).getFile();
        }
        return new File(path);
    }

    public static InputStream getInputStream(String path) throws IOException {
        if (StringUtils.isEmpty(path)) {
            throw new FileNotFoundException("未找到文件路径");
        }
        if (path.startsWith(CLASSPATH_RESOURCE_PREFIX)) {
            return new ClassPathResource(path.replaceAll(CLASSPATH_RESOURCE_PREFIX, "")).getInputStream();
        }
        return Files.newInputStream(Paths.get(path));
    }

}